﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;
using System.Globalization;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Collections.Generic;
using System.Web;
using System.Linq;
using System.Reflection;
using System.Text;

namespace BIMP.ADMIN.BIMP
{
    public partial class EditNotification : LayoutsPageBase, IPostBackEventHandler
    {
        private SPSite TargetSite = null;
        private SPWeb TargetWeb = null;
        private SPList _spList = null;
        private string _listUrl = string.Empty;
        private string _serverUrl = string.Empty;
        private Guid NotificationID = Guid.Empty;
        private Guid ListID = Guid.Empty;

        private RmdConfiguration NotificationConfig = null;

        public string GetClassForWizardStep(object wizardStep)
        {
            WizardStep step = wizardStep as WizardStep;

            if (step == null)
            {
                return "";
            }

            int stepIndex = EditNotificationWizard.WizardSteps.IndexOf(step);

            if (stepIndex < EditNotificationWizard.ActiveStepIndex)
            {
                return "stepCompleted";
            }
            else if (stepIndex > EditNotificationWizard.ActiveStepIndex)
            {
                return "stepNotCompleted";
            }
            else
            {
                return "stepCurrent";
            }
        }

        protected void btnFillQuery_Click(object sender, EventArgs e)
        {
        }

        private void FillLabelsAndDefaultValues()
        {
            lblPageTitle.Text = GetLocalizedString("Page_EditNotification_PageTitle");
            lblPageTitleInTitleArea.Text = GetLocalizedString("Page_EditNotification_PageTitleInTitleArea");

            ddlType.Items.Add(new ListItem(RmdType.Item.ToString()));
            ddlType.Items.Add(new ListItem(RmdType.Bulk.ToString()));
            ddlType.Items.Add(new ListItem(RmdType.Summary.ToString()));

        }

        protected void Page_Load(object sender, EventArgs e)
        {
            FillLabelsAndDefaultValues();


            EditNotificationWizard.PreRender += (s, evnt) =>
            {
                Repeater SideBarList = EditNotificationWizard.FindControl("HeaderContainer").FindControl("SideBarList") as Repeater;

                SideBarList.DataSource = EditNotificationWizard.WizardSteps;
                SideBarList.DataBind();
            };


            string strSiteUrl = Request.QueryString["SiteUrl"].ToString();
            TargetSite = new SPSite(strSiteUrl);
            TargetWeb = TargetSite.OpenWeb();//SPControl.GetContextWeb(HttpContext.Current);
            
            ListID = new Guid(this.Request.QueryString.GetValues("ListId")[0]);
            _spList = TargetWeb.Lists.GetList(ListID, true);

            try
            {
                NotificationID = new Guid(this.Request.QueryString.GetValues("NotificationID")[0]);
            }
            catch(Exception exc)
            {
            }
            
            NotificationConfig = _spList.GetNotification(NotificationID);
            if (NotificationConfig == null)
                NotificationConfig = new RmdConfiguration();
            else
                if (!Page.IsPostBack)
                    LoadSettings();

            using (SPWeb web = this._spList.ParentWeb)
            {
                _listUrl = SPHttpUtility.HtmlEncode(string.Format("{0}/{1}", web.ServerRelativeUrl, _spList.RootFolder.Url.Trim()));
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
        }

        private string GetLocalizedString(string resourceKey)
        {
            return SPUtility.GetLocalizedString("$Resources:" + resourceKey, "BIMP", (uint)CultureInfo.CurrentUICulture.LCID);
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
        }

        public void RaisePostBackEvent(string eventArgument)
        {
        }

        protected void WizardNextButton_OnClick(object sender, WizardNavigationEventArgs ea)
        {

            //xslt
            if (ea.CurrentStepIndex == EditNotificationWizard.WizardSteps.Count - 4)
            {
                SaveSettings();
                NotificationEngine engine = new NotificationEngine(NotificationConfig);
                
                lbAllowedBindings.Items.Clear();
                foreach (var s in engine.Strategy.AllowedBindings)
                    lbAllowedBindings.Items.Add(new ListItem(s));
            }
            //preview
            if (ea.CurrentStepIndex == EditNotificationWizard.WizardSteps.Count - 3)
            {
                SaveSettings();
                try
                {
                    NotificationEngine engine = new NotificationEngine(this.NotificationConfig);

                    try
                    {
                        var nodes = engine.Strategy.GetEMailNodes();
                        
                        StringBuilder sb = new StringBuilder();
                        
                        foreach (var n in nodes)
                        {
                            var nodeXml = n.ToString();
                            sb.AppendLine(nodeXml);
                            sb.AppendLine(new string('=', 20));
                        }

                        outputHTML.Text = sb.ToString();

                        if (string.IsNullOrEmpty(outputHTML.Text))
                            outputHTML.Text =
@"Result XML should be smth like that:
 <EMails>
    <EMail>
        <FROM Address=""someone@troika.ru"" />
        <TO>
            <Recipient Address=""Someone@troika.ru"" />
            <Recipient Address=""Someone@troika.ru"" />
        </TO>
        <CC>
            <Recipient Address=""Someone@troika.ru"" />
            <Recipient Address=""Someone@troika.ru"" />
        </CC>
        <BCC>
            <Recipient Address=""Someone@troika.ru"" />
            <Recipient Address=""Someone@troika.ru"" />
        </BCC>
        <SUBJECT>Hello World</SUBJECT>
        <BODY IsHtml=""false"">
        </BODY>
    </EMail>

    ...
    ...

 </EMails>

* Please note all xml nodes and attributes are required except of CC, BCC.
";
                    }
                    catch (Exception exc)
                    {
                        outputHTML.Text = exc.ToString();
                    }
                }
                catch (Exception exc)
                {
                    outputHTML.Text = exc.ToString();
                }
            }

        }

        protected void WizardFinishButton_OnClick(object sender, WizardNavigationEventArgs ea)
        {
            SaveSettings();
            _spList.AddNotification(NotificationConfig);
            SPUtility.TransferToSuccessPage("Gotcha !");
        }

        private void LoadSettings()
        {
            iftbNotificationName.Text = NotificationConfig.DisplayName;
            
            if(NotificationConfig.Schedule != null)
                (JobSchedule as SchedulePicker).Schedule = NotificationConfig.Schedule;
            
            iftbXSLT.Text = NotificationConfig.XslTransform;
            iftbDSCFG.Text = NotificationConfig.DataSourceCFG;
        }


        private bool SaveSettings()
        {
            NotificationConfig.SiteId = TargetWeb.Site.ID;
            NotificationConfig.WebId = TargetWeb.ID;
            NotificationConfig.ListId = ListID;
            NotificationConfig.DisplayName = iftbNotificationName.Text;
            NotificationConfig.XslTransform = iftbXSLT.Text;
            NotificationConfig.DataSourceCFG = iftbDSCFG.Text;

            try
            {
                SPSchedule schedule = (JobSchedule as SchedulePicker).Schedule;
                NotificationConfig.Schedule = schedule;
            }
            catch
            {
            }
            NotificationConfig.XslTransform = iftbXSLT.Text;
            NotificationConfig.AuthorID = SPContext.Current.Web.CurrentUser.LoginName;
            return true;
        }
    }
}
